package cn.sc.summer.job.dalayqueue;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 类名：延时任务，此延时任务是由新线程进行执行，故不能获取主线程之间参数信息
 *
 * @author a-xin
 * @date 2023/12/15 10:10
 */
@Data
@AllArgsConstructor
public class DelayTask implements Delayed {

    /**
     * 任务方法，另起线程执行
     */
    final private Function<Object, ?> task;

    /**
     * 执行参数信息
     */
    final private Object arg;

    /**
     * 任务描述
     */
    final private String desc;

    /**
     * 执行次数
     */
    final private Integer number;

    /**
     * 任务ID
     */
    final private String id;

    /**
     * 延迟时间，ms
     */
    final private long expire;

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), unit);
    }

    @Override
    public int compareTo(Delayed delayed) {
        long delta = getDelay(TimeUnit.NANOSECONDS) - delayed.getDelay(TimeUnit.NANOSECONDS);
        return (int) delta;
    }

}
